package hos.concurrence.utils;

import android.annotation.SuppressLint;
import android.os.Build;

import java.util.concurrent.Executor;
import java.util.concurrent.Future;

import java9.util.concurrent.CompletableFuture;

/**
 * <p>Title: FutureUtils </p>
 * <p>Description: Future兼容工具类 </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023/8/7 10:59
 */
@SuppressWarnings("rawtypes")
public class FutureUtils {

    public static Future[] newCompletableFuture(int size) {
        if (Build.VERSION.SDK_INT >= 24) {
            return new java.util.concurrent.CompletableFuture[size];
        }
        try {
            Class.forName("java.util.concurrent.CompletableFuture");
            return new java.util.concurrent.CompletableFuture[size];
        } catch (ClassNotFoundException e) {
            // 不存在，调用外在方法
            return new CompletableFuture[size];
        }
    }

    @SuppressLint("NewApi")
    public static Future allOf(Future[] futures) {
        if (futures instanceof java.util.concurrent.CompletableFuture[]) {
            // 24 版本才可以使用
            return java.util.concurrent.CompletableFuture.allOf((java.util.concurrent.CompletableFuture[]) futures);
        }
        return CompletableFuture.allOf((CompletableFuture[]) futures);
    }

    @SuppressLint("NewApi")
    public static Future<Void> runAsync(Runnable runnable,
                                        Executor executor) {
        if (Build.VERSION.SDK_INT >= 24) {
            return java.util.concurrent.CompletableFuture.runAsync(runnable, executor);
        }
        try {
            Class.forName("java.util.concurrent.CompletableFuture");
            return java.util.concurrent.CompletableFuture.runAsync(runnable, executor);
        } catch (ClassNotFoundException e) {
            // 不存在，调用外在方法
            return CompletableFuture.runAsync(runnable, executor);
        }
    }
}
